'use strict';
const db = uniCloud.database();
const dbcmd = db.command;
const {
	result_success,
	result_error
} = require('http-result-modle')
const {
	payNotifyUrl
} = require('config-current-space')
const {
	mainSpaceId
} = require('config-main-space')
const {
	XMLParser
} = require("fast-xml-parser");
const crypto = require("crypto");
const mycloud = uniCloud.init({
	provider: 'tencent',
	spaceId: mainSpaceId
})

function getSign(str) {
	let hash = crypto.createHash('md5').update(str, 'utf8');
	return hash.digest('hex').toUpperCase();
}

function get_nonce_str(len) {
	let str = '';
	while (str.length < len) {
		str += Math.random().toString(36).slice(2);
	}
	return str.slice(-len);
}
exports.main = async (event, context) => {
	let code = event.queryStringParameters.code
	let appid = 'wx257947eb60116e44'
	let secret = 'fe54fb1f85730042ab5446c95893804a'
	let url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appid + '&secret=' + secret +
		'&code=' + code + '&grant_type=authorization_code'
	let res = await uniCloud.httpclient.request(url, {
		method: 'POST',
		dataType: 'text'
	})
	let openid = ''
	if (res.status === 200) {
		let data = JSON.parse(res.data)
		if(!data.errcode){
			openid = data.openid
		}else{
			return result_error(data)
		}
	}
	let dataId = event.queryStringParameters.dataId
	let phone = event.queryStringParameters.phone
	let orderId = event.queryStringParameters.orderId
	let finger = event.queryStringParameters.finger
	let channel = event.queryStringParameters.channel
	let taskInfoResult = await db.collection('wmz-entitlement').doc(dataId).get();
	taskInfoResult = taskInfoResult.data[0]
	taskInfoResult.price = (taskInfoResult.price - Math.random() / 10).toFixed(2)
	let appletInfo= await db.collection('wmz-applet-info').doc(taskInfoResult.app_id).get();
	appletInfo=appletInfo.data[0]
	if (!appletInfo.balance || appletInfo.balance < 10) {
		return  result_error('余额不足')
	}  
	res = await db.collection('wmz-entitlement-order').add({
		user_id: phone,
		entitlement_id: taskInfoResult._id,
		entitlement_name: taskInfoResult.name,
		create_time: new Date().getTime(),
		wechat_user_id: openid,
		status: '待付款',
		coupon_data: taskInfoResult.coupon_data,
		phone: phone,
		orderId: orderId,
		finger: finger,
		channel: channel,
		money: taskInfoResult.price,
		pla: 'wmz',
		shop_id: appletInfo._id,
		app_id: appletInfo._id,
		pay_app_id: appletInfo.alipay.pay_app_id
	})
	if (!res.inserted) {
		return  result_error('新增订单数据失败')
	}
	
	let mch_id = '1580825441'
	let notify_url = payNotifyUrl+'/notify-entitlement/wechat'
	let out_trade_no = res.id
	let spbill_create_ip = '127.0.0.1'
	let total_fee = '1'
	let body = '开通会员'
	url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
	let key = "NaxuIB3FPyj5uLp8aSYZsv0TrgYuVaw1"
	let obj = {
		appid: appid,
		mch_id: mch_id,
		openid: openid,
		nonce_str: get_nonce_str(32),
		notify_url: notify_url,
		out_trade_no: out_trade_no,
		spbill_create_ip: spbill_create_ip,
		total_fee: total_fee,
		trade_type: "JSAPI",
		fee_type: "CNY",
		body: body
	}
	let arr = Object.keys(obj).sort().map(item => {
		return `${item}=${obj[item]}`;
	});
	let str = arr.join('&') + '&key=' + key;
	let sign = getSign(str);
	res = await uniCloud.httpclient.request(url, {
		method: 'POST',
		data: '<xml>' +
			'<appid>' + obj.appid + '</appid>' +
			'<mch_id>' + obj.mch_id + '</mch_id>' +
			'<openid>' + obj.openid + '</openid>' +
			'<nonce_str>' + obj.nonce_str + '</nonce_str>' +
			'<notify_url>' + obj.notify_url + '</notify_url>' +
			'<out_trade_no>' + obj.out_trade_no + '</out_trade_no>' +
			'<spbill_create_ip>' + obj.spbill_create_ip + '</spbill_create_ip>' +
			'<total_fee>' + obj.total_fee + '</total_fee>' +
			'<trade_type>' + obj.trade_type + '</trade_type>' +
			'<fee_type>' + obj.fee_type + '</fee_type>' +
			'<body>' + obj.body + '</body>' +
			'<sign>' + sign + '</sign>' +
			'</xml>',
		dataType: 'text' // 指定返回值为json格式，自动进行parse
	})
	console.log(res)
	let xml = res.data
	const parser = new XMLParser();
	let rData = parser.parse(xml);
	rData = rData.xml
	if (rData.return_code === "SUCCESS") {
		if (rData.result_code === "SUCCESS") {
			let obj = {
				appId: appid,
				timeStamp: new Date().getTime() + "",
				package: "prepay_id=" + rData.prepay_id,
				nonceStr: rData.nonce_str,
				signType: "MD5"
			}
			let arr = Object.keys(obj).sort().map(item => {
				return `${item}=${obj[item]}`;
			});
			let str = arr.join('&') + '&key=' + key;
			obj.paySign = getSign(str);
			return result_success(obj)
		} else {
			return result_error(rData)
		}
	} else {
		return result_error(rData.return_msg)
	}
};